<?php
add_action('widgets_init', 'register_top_category_home_widget'); // load widget

function register_top_category_home_widget() { // register widget
    register_widget('top_category_home');
}

class top_category_home extends WP_Widget {// widget class {

    function top_category_home() { 
    // widget setting | class name must be same function name
        $widget_ops = array('classname' => 'Lastest news-w', 'description' =>
            'Display top Category Home page');
        $control_ops = array(
            'width' => 250,
            'height' => 350,
            'id_base' => 'top_category_home');
        $this->WP_Widget('top_category_home', 'CouponX - top Category Home page', $widget_ops, $control_ops);
    }

    function widget($args, $instance) {
        global $wpdb, $table_prefix;
        $title = apply_filters('widget_title', $instance['title']);
        $my_query = "
            SELECT term_id as cat_id FROM ".$table_prefix."term_taxonomy WHERE taxonomy='store_category' AND parent = 0
        ";
        $categories = $wpdb->get_results($my_query);
        ?>
        
        <div class="textlink">
        <div class="row-fluid ti">
            <span id="down-category"></span>
            <span id="up-category"></span>
            <p><?php echo $title;?></p>
        </div>
             <ul id="linkss-category" class="row-fluid col5">
        <?php foreach ($categories as $categorys){
                $parent_id = $categorys->cat_id;
                $term_parent = get_term_by('id',$parent_id,'store_category');
                $parent_name = $term_parent->name;
                $parent_link = get_term_link($term_parent->slug, 'store_category');
        ?>
                 <li class="wrap-top-category">
                     <a href="<?php echo $parent_link;?>" title="<?php echo $parent_name;?>"><?php echo $parent_name;?></a>
                 </li>
        <?php }?>
             </ul>
            <div class="row-fluid show-store">
                <span class="more-categories"><a href="<?php echo home_url('/categories-listing'); ?>">+ more</a></span>
             </div>
        </div>
    <?php }

    function update($new_instance, $old_instance) { // update widget
        $instance = $old_instance;
        $instance['title'] = $new_instance['title'];
        return $instance;
    }

    function form($instance) { // form for the widget options
        ?>
        <div style="color: #333;">
            <p>        
                <label for="<?php echo $this->get_field_id('title'); ?>"><?php echo 'Title'; ?></label>
                <input type="text" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" style="width:90%;" />
            </p>                 
        </div>
        <?php
    }
}
?>
